<template>
  <div >
    <el-image :width="width" :height="height" :src="form.finImageUrl" @click="showPreview" @load="loadSuccess" @error="loadFail">

      <div slot="error" >

        <img :width="width" :height="height" :style="`width:${width}px, height:${height}px`" src="" >
      </div>
    </el-image>
    <el-dialog :visible.sync="form.dialogVisible" >
      <img :src="url" width="100%" alt="">
    </el-dialog>
    <div v-if="text" :style="textStyle">{{ text }}</div>
  </div>
</template>

<script>

import endWith from 'licia/endWith'

export default {
  props: {
    // 图片链接
    url: {
      type: String,
      default: ''
    },
    // 宽度
    width: {
      type: Number,
      default: 60
    },
    // 高度
    height: {
      type: Number,
      default: 60
    },
    // 是否开启预览功能
    preview: {
      type: Boolean,
      default: false
    },
    // 图片质量
    quality: {
      type: Number,
      default: 80
    },
    text: {
      type: String
    }
  },
  data() {
    return {
      form: {
        finImageUrl: '',
        failCount: 0,
        dialogVisible: false,
        loading: true
      }
    }
  },
  computed: {
    textStyle() {
      return 'text-align:center;width:' + this.width + 'px'
    }
  },
  watch: {
    url(value) {
      this.urlChange()
    }
  },
  mounted() {
    this.urlChange()
  },
  methods: {
    // url变换,重新加载图片
    urlChange() {
      this.form.failCount = 0
      // 是图片为空，进入loadFail
      this.form.finImageUrl = ''
    },
    showPreview() {
      if (this.preview) {
        this.form.dialogVisible = true
      }
    },
    loadSuccess() {
    },
    loadFail() {
      if (!this.url) {
        return
      }
      this.form.failCount = this.form.failCount + 1
      if (this.form.failCount === 1) {
        if (endWith(this.url, 'jpg') || endWith(this.url, 'jpeg') || endWith(this.url, 'png')) {
          this.form.finImageUrl = this.url + `?x-oss-process=image/resize,w_${this.width},h_${this.height}/format,jpg/quality,q_${this.quality}`
        } else {
          this.form.finImageUrl = this.url + `?x-oss-process=image/format,jpg/quality,q_${this.quality}`
        }
        return
      }
      if (this.form.failCount === 2) {
        this.form.finImageUrl = this.url
        return
      }
    }
  }
}
</script>

<style scoped>
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 14px;
  }
</style>
